package section

import (
	"context"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type AttachProductToSectionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAttachProductToSectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AttachProductToSectionLogic {
	return &AttachProductToSectionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AttachProductToSectionLogic) AttachProductToSection(in *backend.SectionProductInfo) (*backend.BaseResp, error) {
	// logx.Infof("AttachProductToSection SectionProductInfo : %+v ", in)
	// SectionId:11  BrandId:44089  Sort:1

	if in.SectionId == nil || *in.SectionId == 0 {
		return nil, errorx.NewInvalidArgumentError("common.validationError")
	}

	if (in.ProductId == nil || *in.ProductId == 0) && (in.BrandId == nil || *in.BrandId == 0) && (in.CategoryId == nil || *in.CategoryId == 0) {
		return nil, errorx.NewInvalidArgumentError("common.validationError")
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.SectionProductRelationshipColumns.SectionID] = map[string][]any{
		"equalTo": {*in.SectionId},
	}
	var productId uint64
	if in.ProductId != nil && *in.ProductId > 0 {
		productId = *in.ProductId
		filterMap[model.SectionProductRelationshipColumns.ProductID] = map[string][]any{
			"equalTo": {productId},
		}
	}
	var brandId uint64
	if in.BrandId != nil && *in.BrandId > 0 {
		brandId = *in.BrandId
		filterMap[model.SectionProductRelationshipColumns.BrandID] = map[string][]any{
			"equalTo": {brandId},
		}
	}
	var categoryId uint64
	if in.CategoryId != nil && *in.CategoryId > 0 {
		categoryId = *in.CategoryId
		filterMap[model.SectionProductRelationshipColumns.CategoryID] = map[string][]any{
			"equalTo": {categoryId},
		}
	}
	list, _, err := l.svcCtx.Section.GetRelProductList(l.ctx, model.M{
		"pageSize": uint64(1),
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var rel *model.SectionProductRelationship
	if len(list) > 0 {
		rel = list[0]
		if in.Sort != nil {
			rel.Sort = uint16(*in.Sort)
		}
	} else {
		var sort uint16
		if in.Sort != nil {
			sort = uint16(*in.Sort)
		} else {
			sort = uint16(globalkey.SystemDefaultSort)
		}

		rel = &model.SectionProductRelationship{
			SectionID:  *in.SectionId,
			BrandID:    brandId,
			CategoryID: categoryId,
			ProductID:  productId,
			Sort:       sort,
		}
	}

	err = l.svcCtx.Section.AttachProductToSection(l.ctx, nil, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseResp{
		Msg: i18n.CreateSuccess,
	}, nil
}
